package tedu.rocketmq.controller;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import tedu.rocketmq.param.TeduUser;
import tedu.rocketmq.service.HelloService;

import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
public class HelloController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /*@Autowired
    private DefaultMQProducer producer;*/
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @GetMapping("/hello")
    public String sayHi(String name){
        stringRedisTemplate.opsForValue().set("name","王翠花");
        //1.组织一个消息对象 Message payLoad就是消息体body Object类型
        Message<String> message = MessageBuilder.withPayload(name).build();
        //2.1同步发送syncSend
        /*SendResult sendResult
                = rocketMQTemplate.syncSend(
                        "rocketmq-test-topic:北京", message);*/
        //2.2发送同步消息 延迟处理
        /*SendResult sendResult = rocketMQTemplate.syncSend(
                "rocketmq-test-topic",
                message,
                500,
                5);*/
        //2.3异步发送
        rocketMQTemplate.asyncSend("rocketmq-test-topic", message, new SendCallback() {
                    //异步线程 接收rocketmq反馈
                    //rocketmq反馈成功调用onSuccess
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        //一般逻辑是记录日志
                        System.out.println("成功发送消息");
                    }
                    //rocketmq没有接到消息,接收过程出现问题
                    @Override
                    public void onException(Throwable throwable) {
                        //一般逻辑是记录日志
                        System.out.println("消息发送失败");
                    }
                },500,5
        );
        //2.4 异步消息发送延迟消息
        System.out.println("发送消息结束");
        return "send success";
    }
    @GetMapping("/user")
    public String getUser(TeduUser user){
        Message<TeduUser> message = MessageBuilder.withPayload(user).build();
        rocketMQTemplate.syncSend("user-topic",message);
        return "send ok";
    }
}
